package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.ParamsDTO
import com.abc.robot01.retrofit.bean.PaymentRequest
import com.abc.robot01.retrofit.bean.RequestData
import com.abc.robot01.retrofit.bean.UserOrderDetail
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.json.JSONObject

class WalletViewModel : ViewModel() {
    val TAG = "WalletViewModel"
    private val _types = MutableStateFlow<List<String>>(emptyList())
    val types: StateFlow<List<String>> = _types;

    val amount = mutableStateOf("0.0")

    val success = mutableStateOf(false)

    var base64 by mutableStateOf(
        "iVBORw0KGgoAAAANSUhEUgAAASkAAAEpCAYAAADPmdSCAAAD40lEQVR4nO3UMQEAIAzAMMC/5+GAlx6Jgl7dM7MAqs7vAIAXkwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIM2kgDSTAtJMCkgzKSDNpIA0kwLSTApIMykgzaSANJMC0kwKSDMpIO0CI1AFT7xPGE4AAAAASUVORK5CYII=\n"
    )
    var userOrderId = ""

    fun recharge(value: Double) {
        viewModelScope.launch {
            val a1 = PaymentRequest(
                userId = Robot.userId,
                companyId = Robot.companyId,
                purseType = "COMPANY",
                totalAmount = value,
                pursePayAmount = 0.0,
                thirdPayAmount = 0.0,
                robotId = Robot.robotId,
                source = 3,
                productType = 10,
                userOrderDetailDTOList = listOf(
                    UserOrderDetail(productAmount = value)
                )
            )
            Log.e(TAG, "recharge:" + a1)
            val res = RetrofitService.instance.recharge(
                accessToken = Robot.accessToken,
                userId = Robot.userId,
                companyId = Robot.companyId,
                "WECHAT_NATIVE",
                a1
            )
            base64 = res.data.qrCode
            userOrderId =res.data.userOrderId
            Log.e(TAG, "recharge:" + res)
            Log.e(TAG, "base64:" + base64)
            val r = asyncTaskAsyncTask(type = 6, userOrderId = userOrderId)
            poll();
        }
    }



    /**
     * 轮循
     */
    private suspend fun poll() {
        while (true) {
            delay(2000)
            val a = RetrofitService.instance.pullAsyncTask(
                type = "6",
                sn = Robot.sn,
                rid = Robot.randomId,
                accessToken = Robot.accessToken
            )
            Log.e("PULl", "轮循结果 rid :" + Robot.randomId)
            Log.e("PULl", "轮循结果:" + a)
            if (a.data.status == "PROCESS") {
                Log.e("PULl", "还在处理:")
            } else {
                Log.e("PULl", "充值成功")
                //获取总金额
                getPurseAmount()
                success.value = true
                return
            }
        }
    }

    /**
     *  获取公司钱包余额
     */
    private suspend fun getPurseAmount() {
        RetrofitService.instance.getPurseAmount(Robot.accessToken, Robot.companyId).also {
            amount.value = it.data.toString()
            Log.e("WalletViewModel", "" + it.data)
        }
    }

    /**
     * 获取可充值金额 ,如: 50 100 200 300.
     */
    fun getData() {
        viewModelScope.launch {
            val s = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "COMPANY_CHARGE_AMOUNT"
            ).data
            val a = s.map { it.name }
            _types.value = a
            getPurseAmount()
        }
    }
}


/**
 *  发起异步任务
 */
suspend fun asyncTaskAsyncTask(type: Int = 3, userOrderId: String=""): Boolean {
    Robot.randomId = generateRandomId()
    Log.e("asyncTaskAsyncTask", "发起异步任务 rid:" + Robot.randomId)
    Log.e("userOrderId", "发起异步任务 userOrderId:" + userOrderId)

    val res = RetrofitService.instance.asyncTask(Robot.accessToken,
        RequestData(
            sn = Robot.sn,
            type = type,
            rid = Robot.randomId,
            paramsDTO = ParamsDTO(userOrderId = userOrderId)
        )
    )

    val code = res.code
    if (code != 200) {
        Log.e("asyncTaskAsyncTask", "发起异步任务失败")
        return false
    }
    Log.e("asyncTaskAsyncTask", "发起异步任务成功:" + res)
    return true
}


